package com.jzoom.zoom.pay.alipay;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jzoom.zoom.pay.PayAdapter;
import com.jzoom.zoom.pay.PayAdapterListener;
import com.jzoom.zoom.pay.PayException;
import com.jzoom.zoom.pay.models.Pay;
import com.jzoom.zoom.pay.models.Refund;


public class AlipayAdapter implements PayAdapter {

	private PayAdapterListener listener;
	private AlipayModel model;
	private String notifyUrl;
	
	public AlipayAdapter(String partner, 
			String seller, String privateKey,
			String safeKey, String publicKey) {
		model = new AlipayModel(
				partner, 
				seller, 
				privateKey, 
				safeKey,
				publicKey);
	}
	
	
	public AlipayAdapter(AlipayConfig config){
		model = new AlipayModel(
				config.getPartner(), 
				config.getSeller(), 
				config.getPrivateKey(), 
				config.getSafeKey(),
				config.getPublicKey());
	}
	
	
	private static final Log logger = LogFactory.getLog(AlipayAdapter.class);
	
	
	@Override
	public void onServerNotify(HttpServletRequest request, HttpServletResponse response) {
		try {
			AlipayNotifyInfo info = model.onAliServerNotify(request);
			if(info==null){
				echoFail(response);
			}else{
				logger.info("支付宝回调，支付成功，订单号:"+info.getTransId()+" 内部订单号:"+info.getId());
				listener.onPaySuccess( info );
				echoSuccess(response);
			}
		} catch (Exception e) {
			logger.error(e);
			echoFail(response);
		}
	}
	
	private void echoFail(HttpServletResponse response){
		try {response.getWriter().print("fail");} catch (IOException e) {}
	}
	
	private void echoSuccess(HttpServletResponse response) throws IOException{
		response.getWriter().print("success");
	}
	
	@Override
	public void setPayAdapterListener(PayAdapterListener listener) {
		this.listener = listener;
	}
	
	@Override
	public void setNotifyUrl(String notifyUrl) {
		this.notifyUrl = notifyUrl;
	}
	
	@Override
	public void create(Pay order) throws PayException, IOException {
		String value = model.prePay(order.getId(), order.getTitle(), 
				(double)order.getAmount()/100 , notifyUrl);
		
		Map<String, Object> credential = new HashMap<String, Object>();
		credential.put("payInfo", value);
		
		order.setCredential(credential);
	}
	
	@Override
	public void refund(Refund refund) throws PayException, IOException {
		
	}
	
	@Override
	public void query(Pay pay) throws PayException, IOException {
		
	}

}
